package http

import (
	"context"
	"fmt"
	"gitee.com/Luna-CY/hui-hui/internal/configure"
	"gitee.com/Luna-CY/hui-hui/internal/interface/runner"
	"gitee.com/Luna-CY/hui-hui/internal/logger"
	"gitee.com/Luna-CY/hui-hui/internal/util/data"
	"gitee.com/Luna-CY/hui-hui/internal/util/goroutine"
	"github.com/gin-gonic/gin"
	"net"
	"net/http"
	"sync"
)

// New 创建Runner
func New(listen string, port int) runner.Runner {
	return func(ctx context.Context) (<-chan struct{}, error) {
		var ch = make(chan struct{}, 1)

		goroutine.Go(func() {
			main(ctx, ch, listen, port)
		})

		return ch, nil
	}
}

func main(ctx context.Context, ch chan struct{}, listen string, port int) {
	gin.SetMode(configure.Configure.Server.GinMode)

	var server = gin.New()
	_ = server.SetTrustedProxies(nil)

	server.Use(gin.Recovery())
	if "debug" == configure.Configure.Server.GinMode {
		server.Use(gin.Logger())
	}

	// 注册路由
	logger.GetLogger().Sugar().Info("注册HTTP路由")
	if err := Register(server); nil != err {
		panic(err)
	}

	// http server
	var hs = http.Server{Handler: server}

	// 等待关闭
	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		wg.Done()
		<-ctx.Done()

		logger.GetLogger().Sugar().Info("HTTP服务退出")
		_ = hs.Shutdown(context.Background())

		ch <- struct{}{}
		close(ch)
	}()

	wg.Wait()

	// 注册监听
	var address = fmt.Sprintf("%s:%d", data.Default(listen, "127.0.0.1"), data.Default(port, configure.Configure.Server.Port))
	var listener, err = net.Listen("tcp", address)
	if nil != err {
		panic(err)
	}

	// 启动监听
	logger.GetLogger().Sugar().Infof("HTTP服务已启动，监听地址:%s", address)
	if err := hs.Serve(listener); nil != err && http.ErrServerClosed != err {
		panic(err)
	}
}
